package org.xxpay.core.common.util;

import java.util.LinkedList;
import java.util.List;

/**
 * 分配权重类（待续全面熟读+测试）
 * 参考：https://blog.csdn.net/qq_37751454/article/details/100065713
 */
public class AssignWeightUtil {

    public static class AssignWeight {
        private String name; // 名字
        private int weight;  // 所占权重
        private int count;   // 已分配总量

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getWeight() {
            return weight;
        }

        public void setWeight(int weight) {
            this.weight = weight;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        @Override
        public String toString() {
            return "AssignWeight{" +
                    "name='" + name + '\'' +
                    ", weight=" + weight +
                    ", count=" + count +
                    '}';
        }
    }


    /**
     * 2.2 均匀分配（对2.1的优化）
     * 说明:如a,b,c，需要计算a/(a+b+c)，b/(a+b+c)，c/(a+b+c)
     * 缺点：遍历全部权重项
     * 优点：按照占比分配相对均匀
     * @param list
     * @return
     */
    public static AssignWeight assignUniform(List<AssignWeight> list) {
        if (list == null || list.size() == 0) {
            return null;
        }
        if (list.size() == 1) {
            return list.get(0);
        }

        //降序， 权重最大的在第一位
        list.sort((o1, o2) -> o2.getWeight() - o1.getWeight());

        //计算总值
        int weightTotal = 0;
        int countTotal = 0;
        for (AssignWeight item: list) {
            weightTotal += item.getWeight();
            countTotal += item.getCount();
        }

        //按权重值比例分配
        for (AssignWeight item: list) {
            double weightD = (double) item.getWeight() / weightTotal;  //设置权重占比 = 设置权重 / 全部权重
            double countD = (double) item.getCount() / countTotal;    //已分配占比 = 当前已分配/全部分配数量
            if (countD < weightD) { //已分配占比 不足 设置占比的 则优先考虑分配
                return item;
            }
        }

        return list.get(0); //默认返回权重最高的
    }

    public static void main(String[] args) {
        List<AssignWeight> list = new LinkedList<>();

        AssignWeight assignWeight = new AssignWeight();
        assignWeight.setName("A");
        assignWeight.setWeight(3);
        list.add(assignWeight);

        AssignWeight assignWeight2 = new AssignWeight();
        assignWeight2.setName("B");
        assignWeight2.setWeight(2);
        list.add(assignWeight2);

        AssignWeight assignWeight3 = new AssignWeight();
        assignWeight3.setName("C");
        assignWeight3.setWeight(2);
        list.add(assignWeight3);

        assignWeight.setCount(1); assignWeight2.setCount(2); assignWeight3.setCount(0);


        System.out.println("取值:" + AssignWeightUtil.assignUniform(list));

    }

}
